package xpn.platform.modules.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xpn.platform.common.config.XpnPlatformConfig;
import xpn.platform.common.exception.XpnExceptionCodeEnum;
import xpn.platform.common.response.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;

/**
 * Shiro认证和授权处理的controller，仅起辅助作用，无关紧要。
 * 
 * @author bobatkm Sep 7, 2017
 *
 */
@RestController
public class ShiroAuthController {

	@Autowired
	XpnPlatformConfig xpnPlatformConfig;

	/*
	 * 提示
	 */
	@GetMapping("/hello")
	public String hello() {
		return xpnPlatformConfig.getHello();
	}

	/*
	 * 提供AuthBasic方式登录
	 */
	@GetMapping("/security/basicauth")
	public Object loginAuthBasic() {
		boolean isAuthenticated = SecurityUtils.getSubject().isAuthenticated();
		if (!isAuthenticated) {
			return xpnPlatformConfig.getLogin();
		} else {
			return xpnPlatformConfig.getHello();
		}
	}

	/*
	 * Shiro登录url：当出现未认证的访问时，shiro自动重定向到此url
	 */
	@GetMapping("/security/login")
	public Object login(HttpServletRequest request, HttpServletResponse response) {
		boolean isAuthenticated = SecurityUtils.getSubject().isAuthenticated();
		if (!isAuthenticated) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			String xpnTokenName = xpnPlatformConfig.getSecurity().getAuthenticationTokenName();
			String sessionId = request.getHeader(xpnTokenName);
			if (sessionId == null || "".equals(sessionId)) {
				sessionId = request.getParameter(xpnTokenName);
			}
			if (sessionId == null) {
				return ResponseUtil.fail(XpnExceptionCodeEnum.NEED_AUTHENTICATION);
			} else {
				return ResponseUtil.fail(XpnExceptionCodeEnum.SESSION_OUT_OF_DATE);
			}

		} else {
			return xpnPlatformConfig.getHello();
		}
	}

	/*
	 * Shiro未授权url：当用户无权限访问时，shiro自动重定向到此url
	 */
	@GetMapping("/security/unauthorized")
	public Object unauthorized(HttpServletResponse response) {
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		return ResponseUtil.fail(XpnExceptionCodeEnum.NEED_PERMISSION);
	}
}
